#!/use/bin/python
# coding=utf-8
# 将 服务交互弹窗情况 输出到飞书
import redis
import datetime
import pymysql
import requests
import json
import pandas as pd
from tabulate import tabulate

from dbutils.pooled_db import PooledDB


logDetail = []

# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf', port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.150.109', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',port=3306)  # 1为连接池里的最少连接数
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql,conf=2):
    if conf == 1:
        conn, cur = getConfConnection()
    else:
        conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if(X is None or Y is None):
        return rate
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            round(X * 100/ Y, 2)
    rate = f"{rate}%"
    return rate

# redis
def getReidsConnection():
    redis_info = {
        "host": "172.20.151.90",
        "password": "Coocaa2022",
        "port": 6379,
        "db": 8
    }

    r = redis.Redis(**redis_info, decode_responses=True)
    return r

# 获取交互 弹窗情况
def getShowNum():
    try:
        # 获取当日 弹窗总次数
        show_num = selectNumBySql(
            f"select show_num from analysis_inter_actify_number t where t.ref_date = '{date}'")
        # 获取当日 弹窗成功次数
        show_success_num = selectNumBySql(
            f"select show_success_num from analysis_inter_actify_number t where t.ref_date = '{date}'")
        # 获取当日 重试弹窗出现次数
        show_retry_num = selectNumBySql(
            f"select show_retry_num from analysis_inter_actify_number t where t.ref_date = '{date}'")
        # 获取当日 重试失败弹窗出现次数
        show_retry_fail_num = selectNumBySql(
            f"select show_retry_fail_num from analysis_inter_actify_number t where t.ref_date = '{date}'")
        # 获取当日 服务结束次数
        show_end_num = selectNumBySql(
            f"select show_end_num from analysis_inter_actify_number t where t.ref_date = '{date}'")
        # 获取当日 服务成功结束次数
        show_end_success_num = selectNumBySql(
            f"select show_end_success_num from analysis_inter_actify_number t where t.ref_date = '{date}'")
        # 弹窗成功率
        show_success_rate = selectNumBySql(
            f"select show_success_rate from analysis_inter_actify_number t where t.ref_date = '{date}'")
        # “重试弹窗”出现率
        show_retry_rate = selectNumBySql(
            f"select show_retry_rate from analysis_inter_actify_number t where t.ref_date = '{date}'")
        # “重试失败弹窗”出现率
        show_retry_fail_rate = selectNumBySql(
            f"select show_retry_fail_rate from analysis_inter_actify_number t where t.ref_date = '{date}'")
        # 服务正常结束率
        show_end_success_rate = selectNumBySql(
            f"select show_end_success_rate from analysis_inter_actify_number t where t.ref_date = '{date}'")
        logDetail.append(
            f"1.弹窗总次数{show_num},弹窗成功次数{show_success_num},弹窗成功率{show_success_rate}\n\n")
        logDetail.append(
            f"2.重试弹窗出现次数{show_retry_num},“重试弹窗”出现率{show_retry_rate}\n\n")
        logDetail.append(
            f"3.重试失败弹窗出现次数{show_retry_fail_num},“重试失败弹窗”出现率{show_retry_fail_rate}\n\n")
        logDetail.append(
            f"4.服务结束次数{show_end_num},服务成功结束次数{show_end_success_num},服务正常结束率{show_end_success_rate}\n\n")
        print(logDetail)

    except Exception as e:
        print(e)
    finally:
        print('')


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

#如 2022年12月13号 获取 221213 作为分表后缀
def getdateyyMMdd(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y%m%d')
    re_date = re_date[2:]
    return re_date



def printFeiShu(msg):
    msg_content = "{env}\n\n{msg}".format(env=env, msg="".join(msg))
    print(msg_content)

    payload = {
        "msg_type": "text",
        "content": {
            "text": msg_content
        }
    }

    headers = {
        'Content-Type': 'application/json'
    }

    data = json.dumps(payload)

    # 按照utf-8编码成字节码
    data = data.encode("utf-8")
    #测试机器人
    #url = 'https://open.feishu.cn/open-apis/bot/v2/hook/4238d051-3d9a-438f-9614-eb324f2ea845'
    #正式机器人
    url = "https://open.feishu.cn/open-apis/bot/v2/hook/4b102c84-338a-4bef-87f9-441ecd3f737b"
    response = requests.post(url, data=data, headers=headers)
    print(response.text)

if __name__ == '__main__':
    d =1
    #today = todayYMD()
    date = getdate(d)
    env = f"{date}日期,服务交互弹窗情况"
    print(env)
    getShowNum()
    printFeiShu(logDetail)


